import Phaser from 'phaser'
import { GroupBar } from '../ui/GroupBar.js';
import { NumberUtils } from '../utils/NumberUtils.js';
import { SoundUtils } from '../utils/SoundUtils.js';
import { ResponsiveUtils } from '../utils/ResponsiveUtils.js';

// 黑洞纠错台：读写纠错
export class ModeAScene extends Phaser.Scene {
  rangeMode= 'yi'
  totalRounds= 10
  currentRound= 0
  score= 0

  currentNumber!: number
  correctReading!: string
  options= []

  titleText!: Phaser.GameObjects.Text
  promptText!: Phaser.GameObjects.Text
  feedbackText!: Phaser.GameObjects.Text
  optionButtons: Phaser.GameObjects.Text[] = []
  hudText!: Phaser.GameObjects.Text
  groupBar!: any // 暴露给 MainScene 使用
  responsive!: ResponsiveUtils
  activeTeamIndex= 0 // 0..6

  constructor() {
    super('ModeAScene')
  }

  init(data) {
    this.rangeMode = data.rangeMode || 'yi'
    this.totalRounds = data.totalRounds || 10
  }

  create() {
    console.log('ModeAScene created with range:', this.rangeMode)

    // 初始化响应式系统
    this.responsive = ResponsiveUtils.getInstance()

    // 初始化音效
    SoundUtils.init()

    // 监听场景关闭事件，清理延时调用
    this.events.once('shutdown', () => {
      this.time.removeAllEvents()
    })

    // 监听变化
    this.events.on('rangeChanged', (newRange) => {
      this.rangeMode = newRange
      this.resetRounds()
    })
    this.events.on('roundsChanged', (val) => {
      this.totalRounds = val
      this.resetRounds()
    })

    this.createUI()
    this.resetRounds()
  }

  createUI() {
    // 直接在游戏场景顶部添加切换按钮
    this.createInGameMenu()

    // 标题
    this.titleText = this.add.text(160, 100, '黑洞纠错台：读写纠错', {
      fontSize: '28px', color: '#22D3EE', fontFamily: 'Arial, sans-serif'
    })

    // HUD（轮次与分数）
    this.hudText = this.add.text(1120, 60, '', {
      fontSize: '18px', color: '#9CA3AF', fontFamily: 'Arial, sans-serif'
    }).setOrigin(1, 0)

    // 题目提示区域
    this.promptText = this.add.text(640, 160, '', {
      fontSize: '26px', color: '#D9E8FF', fontFamily: 'Arial, sans-serif', align: 'center'
    }).setOrigin(0.5)

    // 选项按钮容器
    const buttonContainer = this.add.container(640, 340)

    // 创建三个选项按钮（垂直均匀分布）
    const yOffsets = [-90, 0, 90]
    for (let i = 0; i < 3; i++) {
      const button = this.add.text(0, yOffsets[i], '', {
        fontSize: '22px', color: '#D9E8FF', backgroundColor: '#2D3748',
        padding: { x: 24, y: 14 }, fixedWidth: 520, align: 'center'
      }).setOrigin(0.5).setInteractive({ useHandCursor: true })

      button.on('pointerover', () => button.setStyle({ backgroundColor: '#4A5568' }))
      button.on('pointerout', () => button.setStyle({ backgroundColor: '#2D3748' }))
      button.on('pointerdown', () => this.onOptionSelected(i))

      this.optionButtons.push(button)
      buttonContainer.add(button)
    }

    // 反馈文本
    this.feedbackText = this.add.text(640, 540, '', {
      fontSize: '20px', color: '#FDE047', fontFamily: 'Arial, sans-serif', align: 'center'
    }).setOrigin(0.5)

    // 装饰
    this.createDecorations()

    // 小组竞赛条（底部）— 仅允许🌸
    this.groupBar = new GroupBar(this, 20, 620, 1240, 'flower')
    this.add.existing(this.groupBar)

    // 添加重置成绩按钮
    this.createResetButton()

    // 键盘控制现在由 MainScene 全局处理
  }

  createInGameMenu() {
    // 简单的模式切换按钮（位置稍低避免与MainScene冲突）
    const modeB = this.add.text(280, 70, '→ 单位跃迁台', {
      fontSize: '16px', color: '#22D3EE', backgroundColor: '#1F2937', padding: { x: 10, y: 5 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    const modeC = this.add.text(440, 70, '→ 星际对比跳', {
      fontSize: '16px', color: '#22D3EE', backgroundColor: '#1F2937', padding: { x: 10, y: 5 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    modeB.on('pointerdown', () => {
      console.log('Switching to ModeBScene from ModeA')
      SoundUtils.playTransition()
      this.scene.switch('ModeBScene', { rangeMode: this.rangeMode, totalRounds: this.totalRounds })
    })
    modeC.on('pointerdown', () => {
      console.log('Switching to ModeCScene from ModeA')
      SoundUtils.playTransition()
      this.scene.switch('ModeCScene', { rangeMode: this.rangeMode, totalRounds: this.totalRounds })
    })
  }

  createDecorations() {
    // 背景渐变星云（不干扰内容）- 使用 Canvas 纹理
    const texKey = 'nebula_a'
    if (this.textures.exists(texKey)) {
      this.textures.remove(texKey)
    }
    const canvasTex = this.textures.createCanvas(texKey, 1280, 720)
    const ctx = canvasTex.getContext()
    const g = ctx.createRadialGradient(900, 200, 50, 900, 200, 600)
    g.addColorStop(0, 'rgba(76,29,149,0.25)')
    g.addColorStop(1, 'rgba(11,16,32,0.0)')
    ctx.fillStyle = g
    ctx.fillRect(0, 0, 1280, 720)
    canvasTex.refresh()

    const nebulaSprite = this.add.image(0, 0, texKey).setOrigin(0)
    nebulaSprite.setDepth(-10)
    this.tweens.add({ targets, x: -40, duration: 8000, yoyo, repeat: -1, ease: 'Sine.easeInOut' })

    // 星点
    for (let i = 0; i < 40; i++) {
      const x = Math.random() * 1280
      const y = Math.random() * 720
      const star = this.add.circle(x, y, Math.random() * 1.5 + 0.5, 0x9CA3AF, 0.5)
      star.setDepth(-5)
      this.tweens.add({ targets, alpha: 0.2, duration: 1200 + Math.random() * 1500, yoyo, repeat: -1 })
    }
  }

  resetRounds() {
    this.currentRound = 0
    this.score = 0
    this.nextRound()
  }

  nextRound() {
    if (this.currentRound >= this.totalRounds) {
      SoundUtils.playRoundEnd()
      this.promptText.setText('本轮结束！点击任意选项重新开始')
      this.feedbackText.setText(`成绩：${this.score}/${this.totalRounds}`)
      // 允许点击任意选项重启
      this.optionButtons.forEach(btn => btn.setInteractive())
      this.optionButtons.forEach(btn => btn.once('pointerdown', () => this.resetRounds()))
      return
    }
    this.currentRound++
    this.generateNewQuestion()
    this.updateHud()
  }

  updateHud() {
    this.hudText.setText(`第 ${this.currentRound}/${this.totalRounds} 轮  |  得分 ${this.score}`)
  }

  generateNewQuestion() {
    // 生成随机数字
    this.currentNumber = NumberUtils.generateRandomNumber(this.rangeMode)
    this.correctReading = NumberUtils.numberToChineseReading(this.currentNumber)

    // 生成错误选项
    const wrongReadings = NumberUtils.generateWrongReadings(this.correctReading)

    // 组合所有选项并打乱（确保3个选项）
    this.options = [this.correctReading, ...wrongReadings].slice(0, 3)
    while (this.options.length < 3) {
      const extraWrong = this.correctReading + '零'
      if (!this.options.includes(extraWrong)) this.options.push(extraWrong)
      else this.options.push(this.correctReading.replace('十','一十'))
    }
    this.shuffleArray(this.options)
    this.updateUI()
  }

  updateUI() {
    this.promptText.setText(`选择正确读法：${NumberUtils.formatNumber(this.currentNumber)}`)
    this.options.forEach((option, index) => {
      if (this.optionButtons[index]) {
        this.optionButtons[index].setText(option)
        this.optionButtons[index].setStyle({ backgroundColor: '#2D3748' })
        this.optionButtons[index].setInteractive()
      }
    })
    this.feedbackText.setText('')
  }

  onOptionSelected(optionIndex) {
    const selectedOption = this.options[optionIndex]
    const isCorrect = selectedOption === this.correctReading

    // 播放音效
    if (isCorrect) {
      SoundUtils.playCorrect()
    } else {
      SoundUtils.playWrong()
    }

    // 更新按钮颜色
    this.optionButtons.forEach((button, index) => {
      if (index === optionIndex) {
        button.setStyle({ backgroundColor: isCorrect ? '#059669' : '#DC2626' })
      } else if (this.options[index] === this.correctReading) {
        button.setStyle({ backgroundColor: '#059669' })
      } else {
        button.setStyle({ backgroundColor: '#2D3748' })
      }
      button.removeInteractive()
    })

    // 反馈与得分
    if (isCorrect) {
      this.score++
      this.feedbackText.setText('正确！')
      this.feedbackText.setColor('#10B981')
    } else {
      this.feedbackText.setText(`错误：应读作 "${this.correctReading}"`)
      this.feedbackText.setColor('#EF4444')
    }

    // 下一轮 - 只在延时调用中检查场景状态
    this.time.delayedCall(1200, () => {
      if (this.scene.isActive()) {
        this.nextRound()
      }
    })
  }

  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]]
    }
  }

  teamKeyByIndex(): any {
    const keys = ['red','orange','yellow','green','cyan','blue','purple']
    return keys[this.activeTeamIndex]
  }

  // 创建重置成绩按钮
  createResetButton() {
    const resetBtn = this.add.text(1200, 580, '🔄 重置成绩', {
      fontSize: '16px', color: '#FFFFFF', backgroundColor: '#DC2626',
      padding: { x: 12, y: 8 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    // 悬停效果
    resetBtn.on('pointerover', () => {
      resetBtn.setStyle({ backgroundColor: '#B91C1C' })
    })
    resetBtn.on('pointerout', () => {
      resetBtn.setStyle({ backgroundColor: '#DC2626' })
    })

    // 点击事件
    resetBtn.on('pointerdown', () => {
      this.showResetConfirmation()
    })
  }

  // 显示重置确认对话框
  showResetConfirmation() {
    // 创建半透明背景
    const overlay = this.add.rectangle(640, 360, 1280, 720, 0x000000, 0.7)
    overlay.setInteractive()

    // 创建确认对话框
    const dialog = this.add.container(640, 360)
    const dialogBg = this.add.rectangle(0, 0, 400, 200, 0x1F2937)
    const dialogBorder = this.add.rectangle(0, 0, 400, 200).setStrokeStyle(2, 0x374151)

    const title = this.add.text(0, -60, '确认重置', { fontSize: '24px', color: '#FDE047' }).setOrigin(0.5)
    const message = this.add.text(0, -20, '确定要清除所有队伍的成绩吗？', { fontSize: '16px', color: '#D9E8FF' }).setOrigin(0.5)

    const confirmBtn = this.add.text(-80, 40, '确定', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#DC2626', padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    const cancelBtn = this.add.text(80, 40, '取消', {
      fontSize: '18px', color: '#FFFFFF', backgroundColor: '#6B7280', padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    dialog.add([dialogBg, dialogBorder, title, message, confirmBtn, cancelBtn])

    // 确定按钮事件
    confirmBtn.on('pointerdown', () => {
      this.groupBar.resetAll()
      overlay.destroy()
      dialog.destroy()
      console.log('黑洞纠错台成绩已重置')
    })

    // 取消按钮事件
    cancelBtn.on('pointerdown', () => {
      overlay.destroy()
      dialog.destroy()
    })

    // 点击背景关闭
    overlay.on('pointerdown', () => {
      overlay.destroy()
      dialog.destroy()
    })
  }

  // 响应式处理
  handleResize(gameSize) {
    console.log(`ModeAScene resize: ${gameSize.width}x${gameSize.height}`)

    // 应用响应式缩放
    this.responsive.applyGlobalScale(this)
  }

  destroy() {
    this.events.off('rangeChanged')
    super.destroy()
  }
}
